<?php

namespace App\Admin\Controllers;

use Encore\Admin\Auth\Database\Administrator;
use Encore\Admin\Auth\Database\Role;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Http\Request;
use App\Admin\Extensions\ExcelExpoter;
use DB;
use Encore\Admin\Show;
use App\Models\Casual_xc_record;
use App\Models\Casual_xc_res;
use App\Models\Full_xc_ques;
use App\Models\Casual_xc_ques_type;
use App\Models\Department;
use App\Models\Campus;
use Illuminate\Support\Facades\Input;

class Handle_entranceController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    

    public function index()
    {
        return Admin::content(function (Content $content){
            $content->header('全部问题');
            $content->description('列表');
            
            $content->body($this->grid());
            $content->body($this->img_modal());
        });
    }
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header(trans('问题'));
            $content->description(trans('admin.edit'));

            $content->body($this->form()->edit($id));
        });
    }

    public function show($id, Content $content)
    {
        $ques = Casual_xc_record::find($id);
        
        //根据ID获取记录详情
        if ($ques->compus=='2') {
            $ques_detail['compus'] = '七彩校区';
        }
        if ($ques->compus=='1') {
            $ques_detail['compus'] = 'C86校区';
        }
        if ($ques->compus=='3') {
            $ques_detail['compus'] = '其他';
        }
        //$ques_detail['compus'] = Campus::where('id',$ques->compus)->value('name');
        $ques_detail['ques_type'] = Casual_xc_ques_type::where('id',$ques->ques_type_id)->value('type_name');
        $ques_detail['dep'] = Department::where('id',$ques->dep_id)->value('name');
        $ques_detail['ques_desc'] = $ques->ques_desc;
        $ques_detail['ques_img'] = $ques->ques_img;
        $ques_detail['handle_desc'] = $ques->handle_desc;
        $ques_detail['handle_img'] = $ques->handle_img;
        $ques_detail['end_date'] = $ques->end_date;
        if ($ques->is_handled=='0' ) {
            $ques_detail['handle_status'] = '未处理';
            if ($ques->is_changqi=='1'&&$ques->end_date<date('Y-m-d 12:00:00')) {
               $ques_detail['handle_status'] = '逾期未处理';
            }elseif($ques->is_changqi=='1'&&$ques->end_date>date('Y-m-d 12:00:00')) {
                $ques_detail['handle_status'] = '长期处理中';
            }
        }
        elseif ($ques->is_handled=='1') {
            if ($ques->is_changqi=='1'&&$ques->end_date<date('Y-m-d 12:00:00')) {
                $ques_detail['handle_status'] = '逾期解决';
            }
            else{
                $ques_detail['handle_status'] =  '已处理';
            }
        }
        if (!is_null($ques->xc_res_id)&&is_null($ques->ques_id)) {
            $ques_detail['res'] = $this->get_res_full_name($ques->xc_res_id);
        }else{
            $ques_detail['res'] = full_xc_ques::where('id',$ques->ques_id)->value('ques_title');
        }
        $ques_detail['created_at'] = $ques->created_at;
        return Admin::content(function (Content $content) use ($ques_detail) {
            
            //dd($ques_detail);
            $content->header($ques_detail['res']);
            $content->description(date('Y-m-d',strtotime($ques_detail['created_at'])));

            $content->body(view('admin.xunchang.ques_detail',compact('ques_detail')));
        });
        
    }
    protected function grid()
    {
        return Admin::grid(Casual_xc_record::class, function (Grid $grid) {
            $grid->model()->where('status', '0');
            $grid->model()->orderBy('created_at','desc');
            // $grid->id(trans('admin.ID'))->sortable();
            $grid->xc_type("分类")->display(function($xc_type){
                if ($this->xc_type=='1') {
                    return "偶发巡场";
                }
                if ($this->xc_type=='2') {
                    return "全场巡场";
                }
            })->sortable();
            $grid->column('发生位置')->display(function(){
                if (!is_null($this->xc_res_id)) {
                    $res_full_name = '';
                    //上一级点位ID
                    $parent_res1 = Casual_xc_res::where('id',$this->xc_res_id)->pluck('res_name','pid')->toArray();
                    //dd($parent_res1);
                    //上2级点位ID
                    foreach ($parent_res1 as $key1 => $value1) {
                        $parent_res2 = Casual_xc_res::where('id',$key1)->pluck('res_name','pid')->toArray();
                        //dd($parent_res2);
                        if ($key1!=0) {
                            foreach ($parent_res2 as $key2 => $value2) {
                                $parent_res3 = Casual_xc_res::where('id',$key2)->pluck('res_name','pid')->toArray();
                                //dd($parent_res3);
                                //如果没到顶，则接着找出上3级点位id
                                if ($key2!=0) { 
                                    foreach ($parent_res3 as $key3 => $value3) {
                                        $parent_res4 = Casual_xc_res::where('id',$key3)->pluck('res_name','pid')->toArray();
                                        //dd($parent_res4);
                                        if ($key3!=0) {
                                            foreach ($parent_res4 as $key4 => $value4) { 
                                                $res_full_name .= $value4.">".$value3.">".$value2.">".$value1;
                                                //dd($res_full_name);
                                            }
                                        }
                                        else{
                                            $res_full_name .= $value3.">".$value2.">".$value1;
                                        }
                                    }
                                }else{
                                    //到顶
                                    $res_full_name .= $value2.">".$value1;
                                }
                            }
                        }else{
                            $res_full_name .= $value1;
                        }  
                    }
                    return $res_full_name;
                }
                if (!is_null($this->ques_id)) {
                    return full_xc_ques::where('id',$this->ques_id)->value('ques_title');
                }
            });
            $grid->created_at('发现时间')->sortable();
            $grid->compus('校区')->display(function($compus){
                if ($this->compus=='2') {
                    return "七彩校区";
                }
                if ($this->compus=='1') {
                    return "C86校区";
                }
                if ($this->compus=='3') {
                    return "其他";
                }
                //return Campus::where('id',$this->compus)->value('name');
            })->sortable();
            $grid->ques_type_id('问题种类')->display(function($ques_type_id){
                return Casual_xc_ques_type::where('id',$this->ques_type_id)->value('type_name');
            })->sortable();
            $grid->dep_id('处理部门')->display(function($dep_id){
                return Department::where('id',$this->dep_id)->value('name');
            })->sortable();
            $grid->ques_desc('问题描述');
            $grid->ques_img('图片备注')->display(function($ques_img){
                if (!is_null($this->ques_img)) {
                    $imgs = explode(";", $this->ques_img);
                    //return '<a style="cursor:pointer;" data-toggle="modal" data-target="#myModal" onclick="get_img_url('.$this->ques_img.')">'.count($imgs)."张</a>";
                    return '<a style="cursor:pointer;" data-toggle="modal" data-target="#myModal" data-img="'.$this->ques_img.'">'.count($imgs)."张</a>";
                }else{
                    return "N/A";
                }
                
            });
            $grid->column('状态')->display(function(){
                if ($this->is_handled=='0' ) {
                    if ($this->is_changqi=='1'&&$this->end_date<date('Y-m-d 12:00:00')) {
                       return '逾期未处理';
                    }elseif($this->is_changqi=='1'&&$this->end_date>date('Y-m-d 12:00:00')) {
                        return '长期处理中';
                    }else{
                        return '未处理';
                    }
                }
                elseif ($this->is_handled=='1') {
                    return  '已处理';
                }
            });
            
            $grid->handle_user_id('处理人')->display(function($handle_user_id){
                if ($this->is_handled=='1') {
                    return DB::table('admin_users')->where('id',$this->handle_user_id)->value('username');
                }else{
                    return 'N/A';
                }
                
            });
            $grid->disableCreateButton();
            // $grid->disableExport();
            $filename="问题列表";
            $grid->exporter(new ExcelExpoter($grid,$filename));
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    $batch->disableDelete();
                });
            });
            // $grid->disableRowSelector();
            // $grid->expandFilter();
            $grid->actions(function ($actions) {
                if($actions->row['is_handled']=='1')
                {
                    $actions->disableEdit();
                }
                $actions->disableDelete();
            });

            $grid->filter(function ($filter) {
                $filter->column(1/2,function($filter){
                    $filter->disableIdFilter();
                    $filter->equal('is_handled','处理状态')->select(['0'=>'未处理','1'=>'已处理']);
					$filter->between('created_at', '日期选择')->date();
                });
                $filter->column(1/2,function($filter){
					$filter->equal('dep_id','处理部门')->select(Department::where('id','>','1')->pluck('name','id'));
                });
            });
        });
    }
    protected function img_modal()
    {
        return view('admin.xunchang.img_modal');
    }
    protected function form()
    {
        return Admin::form(Casual_xc_record::class, function (Form $form) {
            $form->display('id', 'ID');
            $form->select('compus', '校区')->options(Campus::all()->pluck('name','id'));
            $form->select('ques_type_id', '问题种类')->options(Casual_xc_ques_type::all()->pluck('type_name', 'id'));
            $form->select('dep_id', '处理部门')->options(Department::where('id','>','1')->pluck('name', 'id'));
            
            $form->display('ques_desc', '问题描述');
            $form->display('ques_img', '图片')->with(function ($ques_img) {
                $img_div = '';
                if (is_null($ques_img)) {
                    return '没有上传图片！';
                }else
                {
                    $imgs = explode(';', $ques_img);
                }

                for ($i=0; $i < count($imgs); $i++) { 
                    $img_div .= "<img src='{$imgs[$i]}' height='200' width='200'/>&nbsp;&nbsp;&nbsp;"; 
                }
                //dd($img_div);
                return $img_div;
                
            });
            $form->tools(function (Form\Tools $tools) {
                // 去掉`列表`按钮
                $tools->disableList();
                // 去掉`删除`按钮
                $tools->disableDelete();
                // 去掉`查看`按钮
                $tools->disableView();
            });
            $form->footer(function ($footer) {
                // 去掉`重置`按钮
                $footer->disableReset();
                // 去掉`查看`checkbox
                $footer->disableViewCheck();
                // 去掉`继续编辑`checkbox
                $footer->disableEditingCheck();
            });
        });
    }

    public function my_index(Request $request)
    {
        $date = isset($request['date'])?$request['date']:date('Y-m-d');
        return Admin::content(function (Content $content) use($date) {
            $content->header("处理入口");
            $content->description(" ");

            $content->body($this->navigation_view($date));
        });
    }

    public  function navigation_view($date)
    {
        $start_date = $date;
        $end_date = $start_date." 23:59:59";
        //今天总计发现
        $faxian = Casual_xc_record::where('status','0')->whereBetween('created_at',[$start_date." 00:00:00",$end_date])->count();
        //dd($faxian);
        //今天已处理
        $done = Casual_xc_record::where(['status'=>'0','is_handled'=>'1'])->whereBetween('created_at',[$start_date." 00:00:00",$end_date])->count();
        //今天还未处理
        $todo = Casual_xc_record::where(['status'=>'0','is_handled'=>'0'])->whereBetween('created_at',[$start_date." 00:00:00",$end_date])->count();
        //部门
        $dep = Department::where('id','>','1')->pluck('name','id')->toArray();
        foreach ($dep as $key => $value) {
            //查出各部门未解决问题数量
            $dep_todo_ques[$key] = Casual_xc_record::where(['is_handled'=>'0','dep_id'=>$key,'status'=>'0'])->count();
            // //查出各部门对应日期总计发现问题数量
            // $dep_faxian_ques[$key] = Casual_xc_record::where(['dep_id'=>$key,'status'=>'0'])->whereBetween('created_at',[$start_date." 00:00:00",$end_date])->count();
            // //查出各部门长期问题数量
            // $dep_changqi_ques[$key] = Casual_xc_record::where(['is_handled'=>'0','dep_id'=>$key,'is_changqi'=>'1','status'=>'0'])->where('end_date','>',date('Y-m-d H:i:s'))->count();
            // //查出各部门长期问题数量
            // $dep_yuqi_ques[$key] = Casual_xc_record::where(['is_handled'=>'0','dep_id'=>$key,'is_changqi'=>'1','status'=>'0'])->where('end_date','<',date('Y-m-d H:i:s'))->count();
        }
        //var_dump($start_date);

        return view('admin.xunchang.handle_navigation_view',compact('start_date','faxian','done','todo','dep','dep_todo_ques','dep_faxian_ques','dep_changqi_ques','dep_yuqi_ques'));
    }

    public  function to_handle_ques(Request $request)
    {
        return Admin::content(function (Content $content) use($request) {
            $dep = $request['dep'];
            $ques_status = $request['ques_status'];
            // $date = $request['date'];
            // $ques_num = $request['ques_num'];
            $dep_name = Department::where('id',$dep)->value('name');
            $total_ques_num = Casual_xc_record::where(['status'=>'0','is_handled'=>'0','dep_id'=>$dep])->count();
            $changqi_ques_num = Casual_xc_record::where(['status'=>'0','is_handled'=>'0','dep_id'=>$dep,'is_changqi'=>'1'])->where('end_date','>',date('Y-m-d H:i:s'))->count();
            $yuqi_ques_num = Casual_xc_record::where(['status'=>'0','is_handled'=>'0','dep_id'=>$dep,'is_changqi'=>'1'])->where('end_date','<',date('Y-m-d H:i:s'))->count();
            if ($ques_status=='all') {
                $ques_list = DB::table('casual_xc_records')->leftJoin('full_xc_ques',function($join){
                    $join->on('casual_xc_records.ques_id','=','full_xc_ques.id');
                })->leftJoin('casual_xc_ques_types',function($join){
                    $join->on('casual_xc_ques_types.id','=','casual_xc_records.ques_type_id');
                })->where(['is_handled'=>'0','dep_id'=>$dep,'status'=>'0'])->orderBy('casual_xc_records.is_changqi','desc')->get(['casual_xc_records.id','casual_xc_records.compus','casual_xc_records.time_type','casual_xc_records.xc_type','casual_xc_records.xc_res_id','casual_xc_records.dep_id','full_xc_ques.ques_title','full_xc_ques.ques_desc','casual_xc_ques_types.type_name','casual_xc_records.is_changqi','casual_xc_records.end_date','casual_xc_records.ques_desc as xc_desc','casual_xc_records.ques_img','casual_xc_records.xc_user','casual_xc_records.changqi_desc','casual_xc_records.changqi_img'])->toArray();
            }
            if ($ques_status=='changqi') {
                $ques_list = DB::table('casual_xc_records')->leftJoin('full_xc_ques',function($join){
                    $join->on('casual_xc_records.ques_id','=','full_xc_ques.id');
                })->leftJoin('casual_xc_ques_types',function($join){
                    $join->on('casual_xc_ques_types.id','=','casual_xc_records.ques_type_id');
                })->where(['is_handled'=>'0','dep_id'=>$dep,'status'=>'0','is_changqi'=>'1'])->where('end_date','>',date('Y-m-d H:i:s'))->orderBy('casual_xc_records.is_changqi','desc')->get(['casual_xc_records.id','casual_xc_records.compus','casual_xc_records.time_type','casual_xc_records.xc_type','casual_xc_records.xc_res_id','casual_xc_records.dep_id','full_xc_ques.ques_title','full_xc_ques.ques_desc','casual_xc_ques_types.type_name','casual_xc_records.is_changqi','casual_xc_records.end_date','casual_xc_records.ques_desc as xc_desc','casual_xc_records.ques_img','casual_xc_records.xc_user','casual_xc_records.changqi_desc','casual_xc_records.changqi_img'])->toArray();  
            }
            if ($ques_status=='yuqi') {
                $ques_list = DB::table('casual_xc_records')->leftJoin('full_xc_ques',function($join){
                    $join->on('casual_xc_records.ques_id','=','full_xc_ques.id');
                })->leftJoin('casual_xc_ques_types',function($join){
                    $join->on('casual_xc_ques_types.id','=','casual_xc_records.ques_type_id');
                })->where(['is_handled'=>'0','dep_id'=>$dep,'status'=>'0','is_changqi'=>'1'])->where('end_date','<',date('Y-m-d H:i:s'))->orderBy('casual_xc_records.is_changqi','desc')->get(['casual_xc_records.id','casual_xc_records.compus','casual_xc_records.time_type','casual_xc_records.xc_type','casual_xc_records.xc_res_id','casual_xc_records.dep_id','full_xc_ques.ques_title','full_xc_ques.ques_desc','casual_xc_ques_types.type_name','casual_xc_records.is_changqi','casual_xc_records.end_date','casual_xc_records.ques_desc as xc_desc','casual_xc_records.ques_img','casual_xc_records.xc_user','casual_xc_records.changqi_desc','casual_xc_records.changqi_img'])->toArray();
            }
            
            foreach ($ques_list as $key => $value) {
                $ques_list[$key]->xc_res_id = $this->get_res_full_name($ques_list[$key]->xc_res_id);
            }
            
            // dd($ques_list);
            //判断当前登陆用户是否能处理对应部门的问题
            $can_handle = [];
            if(Admin::user()->isAdministrator())
            {
                array_push($can_handle, 1);
                //$can_handle = 1;
            }
            if(Admin::user()->isRole('sup_staff'))
            {
                array_push($can_handle, Department::where('name','校务后勤部')->value('id'));
                //$can_handle = Department::where('name','后勤部')->value('id');
            }
            if(Admin::user()->isRole('teacher'))
            {
                array_push($can_handle, Department::where('name','教学部')->value('id'));
                //$can_handle = Department::where('name','教学部')->value('id');
            }
            if(Admin::user()->isRole('tutor'))
            {
                array_push($can_handle, Department::where('name','德育部')->value('id'));
                //$can_handle = Department::where('name','德育部')->value('id');
            }
            if(Admin::user()->isRole('consultant'))
            {
                array_push($can_handle, Department::where('name','咨询部')->value('id'));
                //$can_handle = Department::where('name','咨询部')->value('id');
            }
            if(Admin::user()->isRole('bookstore_clerk'))
            {
                array_push($can_handle, Department::where('name','书店')->value('id'));
                //$can_handle = Department::where('name','咨询部')->value('id');
            }
            
            //dd($can_handle);
            // $user_dep_id = Admin::user()->dep;
            // //dd($user_dep_id);
            // if ($user_dep_id==$dep||$user_dep_id=='1') {
            //     $can_handle = '1';
            // }else{
            //     $can_handle = '0';
            // }
            //dd($can_handle);
            $content->header($dep_name);
            $content->description("累计未处理问题 (".$total_ques_num.")");

            $content->body(view('admin.xunchang.ques_handle_view',compact('dep','date','ques_list','can_handle','total_ques_num','changqi_ques_num','yuqi_ques_num')));
        });
    }
    

    public function ques_handle_save(Request $request,$record_id)
    {
        //dd(Input::all());
        $handle_desc = Input::get('handle_desc_'.$record_id);
        $handle_imgs = $this->upload($request,'handle_img_'.$record_id);
        if (is_null($handle_imgs)) {
            $handle_img = null;
        }else{
            $handle_img = implode(";", $handle_imgs);
        }
        $end_date = Input::get('end_date_'.$record_id);
        $changqi_desc = Input::get('changqi_desc_'.$record_id);
        $changqi_imgs = $this->upload($request,'changqi_img_'.$record_id);
        if (is_null($changqi_imgs)) {
            $changqi_img = null;
        }else{
            $changqi_img = implode(";", $changqi_imgs);
        }

        if (!empty($end_date)) {
            $is_changqi = '1';
            $is_handled = '0';
        }else{
            $is_changqi = '0';
            $is_handled = '1';
        }
        

        $result = Casual_xc_record::where('id',$record_id)->update([
            'is_handled' => $is_handled,
            'is_changqi' => $is_changqi,
            'handle_user_id' => Admin::user()->id,
            'handle_desc' => $handle_desc,
            'handle_img' => $handle_img,
            'end_date' => $end_date,
            'changqi_desc' => $changqi_desc,
            'changqi_img' => $changqi_img
        ]);

        // if ($result) {
        //     echo "<script>alert('处理成功！');window.location.href='javascript:history.back(-2)';location.reload();</script>";
        // }else{
        //     echo "<script>alert('失败！');window.location.href='javascript:history.back(-2)';location.reload();</script>";
        // }
    }

    public function upload(Request $request,$index){
        $file = $request->file($index);
        //dd($file);
        $filePath =[];  // 定义空数组用来存放图片路径
        if (is_null($file)) {
            $filePath = null;
        }
        else{
            foreach ($file as $fk => $fv) {
                // 判断图片上传中是否出错
                if (!$fv->isValid()) {
                    exit("上传图片出错，请重试！");
                }
                if(!empty($fv)){//此处防止没有多文件上传的情况
                    $allowed_extensions = ["jpg", "jpeg", "gif", "png","bmp"];
                    if ($fv->getClientOriginalExtension() && !in_array($fv->getClientOriginalExtension(), $allowed_extensions)) {
                        exit('您只能上传PNG、JPG、JPEG、BMP或GIF格式的图片！');
                    }
                    $destinationPath = '/upload/xc_img/'.date('Y-m-d'); // public文件夹下面uploads/xxxx-xx-xx 建文件夹
                    $extension = $fv->getClientOriginalExtension();   // 上传文件后缀
                    $fileName = date('YmdHis').mt_rand(100,999).'.'.$extension; // 重命名
                    $fv->move(public_path().$destinationPath, $fileName); // 保存图片
                    $filePath[] = $destinationPath.'/'.$fileName; 
                }
            }
        }
        // 返回上传图片路径，用于保存到数据库中
        return $filePath;
    }

    public function get_res_full_name($res_id)
    {
        $res_full_name = '';
        //上一级点位ID
        $parent_res1 = Casual_xc_res::where('id',$res_id)->pluck('res_name','pid')->toArray();
        //dd($parent_res1);
        //上2级点位ID
        foreach ($parent_res1 as $key1 => $value1) {
            $parent_res2 = Casual_xc_res::where('id',$key1)->pluck('res_name','pid')->toArray();
            //dd($parent_res2);
            if ($key1!=0) {
                foreach ($parent_res2 as $key2 => $value2) {
                    $parent_res3 = Casual_xc_res::where('id',$key2)->pluck('res_name','pid')->toArray();
                    //dd($parent_res3);
                    //如果没到顶，则接着找出上3级点位id
                    if ($key2!=0) { 
                        foreach ($parent_res3 as $key3 => $value3) {
                            $parent_res4 = Casual_xc_res::where('id',$key3)->pluck('res_name','pid')->toArray();
                            //dd($parent_res4);
                            if ($key3!=0) {
                                foreach ($parent_res4 as $key4 => $value4) { 
                                    $res_full_name .= $value4.">".$value3.">".$value2.">".$value1;
                                    //dd($res_full_name);
                                }
                            }
                            else{
                                $res_full_name .= $value3.">".$value2.">".$value1;
                            }
                        }
                    }else{
                        //到顶
                        $res_full_name .= $value2.">".$value1;
                    }
                }
            }else{
                $res_full_name .= $value1;
            }  
        }
        return $res_full_name;
    }
}
